<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>【转载】浅谈控制反转与依赖注入 | Hi, likeqc</title><meta name="keywords" content="转载,IoC,DI"><meta name="author" content="likeqc"><meta name="copyright" content="likeqc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="标题： 浅谈控制反转与依赖注入 - 知乎 (zhihu.com) 作者：胡小国 - 知乎   第一章：小明和他的手机从前有个人叫小明 小明有三大爱好，抽烟，喝酒…… 咳咳，不好意思，走错片场了。应该是逛知乎、玩王者农药和抢微信红包  我们用一段简单的伪代码，来制造一个这样的小明 12345678910111213141516171819202122class Ming extends Perso">
<meta property="og:type" content="article">
<meta property="og:title" content="【转载】浅谈控制反转与依赖注入">
<meta property="og:url" content="http://blog.likeqc.top/posts/a7d7a63d/">
<meta property="og:site_name" content="Hi, likeqc">
<meta property="og:description" content="标题： 浅谈控制反转与依赖注入 - 知乎 (zhihu.com) 作者：胡小国 - 知乎   第一章：小明和他的手机从前有个人叫小明 小明有三大爱好，抽烟，喝酒…… 咳咳，不好意思，走错片场了。应该是逛知乎、玩王者农药和抢微信红包  我们用一段简单的伪代码，来制造一个这样的小明 12345678910111213141516171819202122class Ming extends Perso">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://api.dujin.org/bing/1920.php">
<meta property="article:published_time" content="2021-08-25T11:38:34.000Z">
<meta property="article:modified_time" content="2021-08-25T11:38:34.000Z">
<meta property="article:author" content="likeqc">
<meta property="article:tag" content="转载">
<meta property="article:tag" content="控制反转(IoC)">
<meta property="article:tag" content="依赖注入(DI)">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://api.dujin.org/bing/1920.php"><link rel="shortcut icon" href="/my-img/favicon.png"><link rel="canonical" href="http://blog.likeqc.top/posts/a7d7a63d/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cfc46f9a84ad3fa9ad65d8f0ac94421d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script async="async" src="https://www.googletagmanager.com/gtag/js?id=G-6SZCZCY8XZ"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-6SZCZCY8XZ');
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":365},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":500,"languages":{"author":"作者: likeqc","link":"链接: ","source":"来源: Hi, likeqc","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【转载】浅谈控制反转与依赖注入',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-08-25 19:38:34'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><style type="text/css">.aplayer.aplayer-fixed.aplayer-narrow .aplayer-body{left:-66px!important}.aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover{left:0!important}</style><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://i.loli.net/2020/04/30/C78pkvSPuMRzqUF.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://api.dujin.org/bing/1920.php')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Hi, likeqc</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【转载】浅谈控制反转与依赖注入</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-08-25T11:38:34.000Z" title="发表于 2021-08-25 19:38:34">2021-08-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-25T11:38:34.000Z" title="更新于 2021-08-25 19:38:34">2021-08-25</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="【转载】浅谈控制反转与依赖注入"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/posts/a7d7a63d/#post-comment"><span id="twikoo-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>标题： <a target="_blank" rel="noopener external nofollow noreferrer" href="https://zhuanlan.zhihu.com/p/33492169">浅谈控制反转与依赖注入 - 知乎 (zhihu.com)</a></p>
<p>作者：<a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.zhihu.com/people/hu-xiao-guo-31">胡小国 - 知乎</a></p>
</blockquote>
<hr>
<h2 id="第一章：小明和他的手机"><a href="#第一章：小明和他的手机" class="headerlink" title="第一章：小明和他的手机"></a>第一章：小明和他的手机</h2><p>从前有个人叫小明</p>
<p>小明有三大爱好，抽烟，喝酒…… 咳咳，不好意思，走错片场了。应该是逛知乎、玩王者农药和抢微信红包</p>
<p><img src= "" data-lazy-src="http://img.likeqc.top/img/v2-709d32cb3e9cdd2ead92e40c998ce077_r.jpg" alt="小明的三大爱好"></p>
<p>我们用一段简单的伪代码，来制造一个这样的小明</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">class Ming extends Person</span><br><span class="line">&#123;</span><br><span class="line">    private $_name;</span><br><span class="line"></span><br><span class="line">    private $_age;</span><br><span class="line"></span><br><span class="line">    function read()</span><br><span class="line">    &#123;</span><br><span class="line">        //逛知乎</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function  play()</span><br><span class="line">    &#123;</span><br><span class="line">        //玩农药</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function  grab()</span><br><span class="line">    &#123;</span><br><span class="line">        //抢红包</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>但是，小明作为一个人类，没有办法仅靠自己就能实现以上的功能，他必须<strong>依赖</strong>一部手机，所以他买了一台iphone6，接下来我们来制造一个iphone6</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">class iPhone6 extends Iphone</span><br><span class="line">&#123;</span><br><span class="line">    function read($user=&quot;某人&quot;)</span><br><span class="line">    &#123;</span><br><span class="line">        echo $user.&quot;打开了知乎然后编了一个故事 \n&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function play($user=&quot;某人&quot;)</span><br><span class="line">    &#123;</span><br><span class="line">        echo $user.&quot;打开了王者农药并送起了人头 \n&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function grab($user=&quot;某人&quot;)</span><br><span class="line">    &#123;</span><br><span class="line">        echo $user.&quot;开始抢红包却只抢不发 \n&quot;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>小明非常珍惜自己的新手机，每天把它牢牢<strong>控制</strong>在手心里，所以小明变成了这个样子</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">class Ming extends Person</span><br><span class="line">&#123;</span><br><span class="line">    private $_name;</span><br><span class="line"></span><br><span class="line">    private $_age;</span><br><span class="line"></span><br><span class="line">    public function  __construct()</span><br><span class="line">    &#123;</span><br><span class="line">        $this-&gt;_name = &#x27;小明&#x27;;</span><br><span class="line">        $this-&gt;_age = 26;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function read()</span><br><span class="line">    &#123;</span><br><span class="line">        //……  省略若干代码</span><br><span class="line">        (new iPhone6())-&gt;read($this-&gt;_name); //逛知乎</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function  play()</span><br><span class="line">    &#123;</span><br><span class="line">        //……  省略若干代码</span><br><span class="line">        (new iPhone6())-&gt;play($this-&gt;_name);//玩农药</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function  grab()</span><br><span class="line">    &#123;</span><br><span class="line">        //……  省略若干代码</span><br><span class="line">        (new iPhone6())-&gt;grab($this-&gt;_name);//抢红包</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>今天是周六，小明不用上班，于是他起床，并依次逛起了知乎，玩王者农药，并抢了个红包。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ming = new Ming();  //小明起床</span><br><span class="line">$ming-&gt;read();</span><br><span class="line">$ming-&gt;play();</span><br><span class="line">$ming-&gt;grab();</span><br></pre></td></tr></table></figure>

<p>这个时候，我们可以在命令行里看到输出如下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">小明打开了知乎然后编了一个故事 </span><br><span class="line">小明打开了王者农药并送起了人头 </span><br><span class="line">小明开始抢红包却只抢不发</span><br></pre></td></tr></table></figure>

<p>这一天，小明过得很充实，他觉得自己是世界上最幸福的人。</p>
<h2 id="第二章：-小明的快乐与忧伤"><a href="#第二章：-小明的快乐与忧伤" class="headerlink" title="第二章： 小明的快乐与忧伤"></a>第二章： 小明的快乐与忧伤</h2><p>小明和他的手机曾一起度过了一段美好的时光，一到空闲时刻，他就抱着手机，逛知乎，刷微博，玩游戏，他觉得自己根本不需要女朋友，只要有手机在身边，就满足了。</p>
<p>可谁能想到，一次次地系统更新彻底打碎了他的梦想，他的手机变得越来越卡顿，电池的使用寿命也越来越短，一直到某一天的寒风中，他的手机终于耐不住寒冷，头也不回地关了机。</p>
<p>小明很忧伤，他意识到，自己要换手机了。</p>
<p>为了能获得更好的使用体验，小明一咬牙，剁手了一台iphoneX，这部手机铃声很大，电量很足，还能双卡双待，小明很喜欢，但是他遇到一个问题，就是他之前过度依赖了原来那一部iPhone6，他们之间已经深深耦合在一起了，如果要换手机，他就要拿起刀来改造自己，把自己体内所有方法中的iphone6 都换成 iphoneX。</p>
<p><img src= "" data-lazy-src="http://img.likeqc.top/img/v2-e124d9d71c8400e1aab90f652f8d6bcf_720w.jpg" alt="漫长的改造过程"></p>
<p>经历了漫长的改造过程，小明终于把代码中的 iphone6 全部换成了 iphoneX。虽然很辛苦，但是小明觉得他是快乐的。</p>
<p>于是小明开开心心地带着手机去上班了，并在回来的路上被小偷偷走了。为了应急，小明只好重新使用那部刚刚被遗弃的iphone6，但是一想到那漫长的改造过程，小明的心里就说不出的委屈，他觉得自己过于<strong>依赖</strong>手机了，为什么每次手机出什么问题他都要去改造他自己，这不仅仅是<strong>过度耦合</strong>，简直是<strong>本末倒置</strong>，他向天空大喊，我不要再<strong>控制</strong>我的手机了。</p>
<p>天空中的造物主，也就是作为程序员的我，听到了他的呐喊，我告诉他，你不用再控制你的手机了，交给我来管理，把控制权交给我。这就叫做<strong>控制反转</strong>。</p>
<h2 id="第三章：造物主的智慧"><a href="#第三章：造物主的智慧" class="headerlink" title="第三章：造物主的智慧"></a>第三章：造物主的智慧</h2><p>小明听到了我的话，他既高兴，又有一点害怕，他跪下来磕了几个头，虔诚地说到：“原来您就是传说中的造物主，巴格梅克上神。我听到您刚刚说了 <strong>控制反转</strong> 四个字，就是把手机的控制权从我的手里交给你，但这只是您的想法，是一种思想罢了，要用什么办法才能实现控制反转，又可以让我继续使用手机呢？”</p>
<p>“呵“，身为造物主的我在表现完不屑以后，扔下了四个大字，“依赖注入！”</p>
<p>接下来，伟大的我开始对小明进行惨无人道的改造，如下</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">class Ming extends Person</span><br><span class="line">&#123;</span><br><span class="line">    private $_name;</span><br><span class="line"></span><br><span class="line">    private $_age;</span><br><span class="line"></span><br><span class="line">    private $_phone; //将手机作为自己的成员变量</span><br><span class="line"></span><br><span class="line">    public function  __construct($phone)</span><br><span class="line">    &#123;</span><br><span class="line">        $this-&gt;_name = &#x27;小明&#x27;;</span><br><span class="line">        $this-&gt;_age = 26;</span><br><span class="line">        $this-&gt;_phone = $phone;</span><br><span class="line">        echo &quot;小明起床了 \n&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function read()</span><br><span class="line">    &#123;</span><br><span class="line">        //……  省略若干代码</span><br><span class="line">        $this-&gt;_phone-&gt;read($this-&gt;_name); //逛知乎</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function  play()</span><br><span class="line">    &#123;</span><br><span class="line">        //……  省略若干代码</span><br><span class="line">        $this-&gt;_phone-&gt;play($this-&gt;_name);//玩农药</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    function  grab()</span><br><span class="line">    &#123;</span><br><span class="line">        //……  省略若干代码</span><br><span class="line">        $this-&gt;_phone-&gt;grab($this-&gt;_name);//抢红包</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接下来，我们来模拟运行小明的一天</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$phone = new IphoneX(); //创建一个iphoneX的实例</span><br><span class="line">if($phone-&gt;isBroken())&#123;//如果iphone不可用，则使用旧版手机</span><br><span class="line">    $phone = new Iphone6();</span><br><span class="line">&#125;</span><br><span class="line">$ming = new Ming($phone);//小明不用关心是什么手机，他只要玩就行了。</span><br><span class="line">$ming-&gt;read();</span><br><span class="line">$ming-&gt;play();</span><br><span class="line">$ming-&gt;grab();</span><br></pre></td></tr></table></figure>

<p>我们先看一下iphoneX 是否可以使用，如果不可以使用，则直接换成iphone6,然后唤醒小明，并把手机塞到他的手里，换句话说，把他所依赖的手机直接注入到他的身上，他不需要关心自己拿的是什么手机，他只要直接使用就可以了。</p>
<p>这就是<strong>依赖注入</strong>。</p>
<h2 id="第四章：小明的感悟"><a href="#第四章：小明的感悟" class="headerlink" title="第四章：小明的感悟"></a>第四章：小明的感悟</h2><p>小明的生活开始变得简单了起来，而他把省出来的时间都用来写笔记了，他在笔记本上这样写到</p>
<blockquote>
<p>我曾经有很强的控制欲，过度依赖于我的手机，导致我和手机之间耦合程度太高，只要手机出现一点点问题，我都要改造我自己，这实在是既浪费时间又容易出问题。自从我把控制权交给了造物主，他每天在唤醒我以前，就已经替我选好了手机，我只要按照平时一样玩手机就可以了，根本不用关心是什么手机。即便手机出了问题，也可以由造物主直接搞定，不需要再改造我自己了，我现在买了七部手机，都交给了造物主，每天换一部，美滋滋！<br><strong>我也从其中获得了这样的感悟：</strong> 如果一个类A 的功能实现需要借助于类B，那么就称类B是类A的<strong>依赖</strong>，如果在类A的内部去实例化类B，那么两者之间会出现较高的<strong>耦合</strong>，一旦类B出现了问题，类A也需要进行改造，如果这样的情况较多，每个类之间都有很多依赖，那么就会出现牵一发而动全身的情况，<strong>程序会极难维护</strong>，并且很容易出现问题。要解决这个问题，就要把A类对B类的控制权抽离出来，交给一个第三方去做，把控制权反转给第三方，就称作<strong>控制反转（IOC Inversion Of Control）</strong>。<strong>控制反转是一种思想</strong>，是能够解决问题的一种可能的结果，而<strong>依赖注入（Dependency Injection）</strong>就是其最典型的实现方法。由第三方（<strong>我们称作IOC容器</strong>）来控制依赖，把他通过<strong>构造函数、属性或者工厂模式</strong>等方法，注入到类A内，这样就极大程度的对类A和类B进行了<strong>解耦</strong>。</p>
</blockquote>
<h2 id="第五章-小明的困惑"><a href="#第五章-小明的困惑" class="headerlink" title="第五章 小明的困惑"></a>第五章 小明的困惑</h2><p>有一天，小明发现自己在想阅读知乎的时候，读到了这样一行文字。</p>
<p>未完待续…</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined" rel="external nofollow noreferrer">likeqc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.likeqc.top/posts/a7d7a63d/">http://blog.likeqc.top/posts/a7d7a63d/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.likeqc.top" target="_blank">Hi, likeqc</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%BD%AC%E8%BD%BD/">转载</a><a class="post-meta__tags" href="/tags/%E6%8E%A7%E5%88%B6%E5%8F%8D%E8%BD%AC-IoC/">控制反转(IoC)</a><a class="post-meta__tags" href="/tags/%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5-DI/">依赖注入(DI)</a></div><div class="post_share"><div class="social-share" data-image="https://api.dujin.org/bing/1920.php" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/my-img/wechat-pay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/my-img/wechat-pay.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/my-img/alipay-pay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/my-img/alipay-pay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/95e6514b/"><img class="prev-cover" src= "" data-lazy-src="https://api.dujin.org/bing/1920.php" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">git配置用户名的邮箱，全局/单仓库配置</div></div></a></div><div class="next-post pull-right"><a href="/posts/d7aeaffc/"><img class="next-cover" src= "" data-lazy-src="http://img.likeqc.top/img/Docker.svg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">基于ECS快速搭建Docker环境</div></div></a></div></nav><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://i.loli.net/2020/04/30/C78pkvSPuMRzqUF.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">likeqc</div><div class="author-info__description">活到老，学到老</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">38</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div></div><a id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://gitee.com/likeqc"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:i@likeqc.top" rel="external nofollow noreferrer" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="tencent://message/?uin=642876083" rel="external nofollow noreferrer" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="/my-img/wechat-link.png" target="_blank" title="微信"><i class="fab fa-weixin"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">好久不见</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%B8%80%E7%AB%A0%EF%BC%9A%E5%B0%8F%E6%98%8E%E5%92%8C%E4%BB%96%E7%9A%84%E6%89%8B%E6%9C%BA"><span class="toc-text">第一章：小明和他的手机</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%BA%8C%E7%AB%A0%EF%BC%9A-%E5%B0%8F%E6%98%8E%E7%9A%84%E5%BF%AB%E4%B9%90%E4%B8%8E%E5%BF%A7%E4%BC%A4"><span class="toc-text">第二章： 小明的快乐与忧伤</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%B8%89%E7%AB%A0%EF%BC%9A%E9%80%A0%E7%89%A9%E4%B8%BB%E7%9A%84%E6%99%BA%E6%85%A7"><span class="toc-text">第三章：造物主的智慧</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E5%9B%9B%E7%AB%A0%EF%BC%9A%E5%B0%8F%E6%98%8E%E7%9A%84%E6%84%9F%E6%82%9F"><span class="toc-text">第四章：小明的感悟</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AC%AC%E4%BA%94%E7%AB%A0-%E5%B0%8F%E6%98%8E%E7%9A%84%E5%9B%B0%E6%83%91"><span class="toc-text">第五章 小明的困惑</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8df6bb10/" title="Map key 和 value 是否可以为 null">Map key 和 value 是否可以为 null</a><time datetime="2022-04-10T02:02:53.000Z" title="发表于 2022-04-10 10:02:53">2022-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/9ea5c55a/" title="GitBash 设置命令别名">GitBash 设置命令别名</a><time datetime="2022-04-03T12:22:07.000Z" title="发表于 2022-04-03 20:22:07">2022-04-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/858e2a37/" title="CentOS 7 安装 Node.js 和 npm">CentOS 7 安装 Node.js 和 npm</a><time datetime="2022-04-03T12:17:46.000Z" title="发表于 2022-04-03 20:17:46">2022-04-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/5e9ba592/" title="Spring Task 定时任务">Spring Task 定时任务</a><time datetime="2022-01-19T08:00:43.000Z" title="发表于 2022-01-19 16:00:43">2022-01-19</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/80ac0d20/" title="Cron 表达式">Cron 表达式</a><time datetime="2022-01-14T06:29:07.000Z" title="发表于 2022-01-14 14:29:07">2022-01-14</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://api.dujin.org/bing/1920.php')"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2022 By likeqc</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my <a target="_blank" rel="noopener external nofollow noreferrer" href="http://likeqc.top/">home</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'twikoo-6gnu600m88463a0a',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.vemoji)'))
      }
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'twikoo-6gnu600m88463a0a',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      document.getElementById('twikoo-count').innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    GLOBAL_CONFIG_SITE.isPost && getCount()
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !false) {
    if (false) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'twikoo-6gnu600m88463a0a',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (false) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="false" muted></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="富强,民主,文明,和谐,自由,平等,公正,法治,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="null" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/SerokSSR/cdn/meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/no-pjax/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: true,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', 'G-6SZCZCY8XZ', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>